#import mysql_connection
#import getpass
import MySQLdb

class MySQLHandler:
    def __init__(self):
        self.conn = 0
    def get_config(self):
        fd = open("temp/database/mysql_config.cfg")
        mysql_opts = []
        for line in fd:
            mysql_opts.append(str.decode(line,'base64'))
        fd.close()
        return mysql_opts
    def MySQLConnect(self):
        conf = self.get_config()
        conn = MySQLdb.connect("localhost",conf[1],str.decode(conf[2],'base64'),conf[3])
        self.conn = conn
        return conn
    def DoQuery(self,query):
        cursor = self.conn.cursor()
        cursor.execute(query)
        q = cursor.fetchall()
        cursor.close()
        return q
    def Close(self):
        self.conn.close()

mysql = MySQLHandler()
conn = mysql.MySQLConnect()

def Update(equery):
    global mysql, conn
    mysql.DoQuery(equery)
    
def Select(equery):
    global mysql, conn
    query = mysql.DoQuery(equery)
    return query

def Login(user, passwd):
    usr = Select("SELECT user from user where user='"+user+"';")
    if usr == ():
        return "Kein Username " + user + " vorhanden", False
    pwd = Select("SELECT password from user where user='"+user+"';")
    pwd = str.decode(pwd[0][0],'base64')
    if pwd != passwd:
        return "Du hast das falsche Passwort eingegeben", False
    return "Erfolgreich eingeloggt!",True

def CreateAccount(user,passwd,email):
    if Select("SELECT user from user where user='"+user+"';") == ():
        Update("INSERT INTO user (user, password, email) VALUES ('"+user+"','"+str.encode(passwd,'base64')+"','"+email+"')")
        return "Account erfolgreich angelegt!", True
    else:
        return "Der Username \""+user+"\" ist schon vergeben!", False
def Close():
    mysql.Close()

"""usr = raw_input("Username:")
pw = getpass.getpass("Password:")
pw2 = getpass.getpass("Confirm:")
email = raw_input("Email:")

if pw != pw2:
    print "You failed at typing your Password"
else:
    print CreateAccount(usr,pw,email)[0]
"""
